module service.SearchUserService;

import std.stdio;
import message.MsgDefine;
import model;
import repository;
import hunt.logging;
import std.conv : to;

class SearchUserService {

    static message.MsgDefine.User[] searchUser(SearchUserREQ req)
    {
        import model.User;
        UserRepository userRep = new UserRepository;

        scope(exit)
        {
           userRep.entityManager.close();
        }

        //TODO:req.userId 必须是整形，需要加验证

        message.MsgDefine.User[] users;
        logInfof("user before: %s %s", req.key, req.userId);

        if (req.key.length > 0)
        {
            auto user = userRep.findByMobile(req.key);
            if (user !is null)
            {
                users ~= toUser(user);
            }

            logInfof("mobile %d", users.length);

            if (users.length == 0)
            {
                user = userRep.findByUserName(req.key);
                if (user !is null)
                {
                    users ~= toUser(user);
                }

                logInfof("username %d", users.length);
            }
        }

        if (req.userId.length > 0)
        {
            auto user = userRep.findAllByUID(req.userId);
            if (user !is null)
            {
                users ~= toUser(user);
            }
            logInfof("userId %d", users.length);
        }
      
        return users;
    }


  static message.MsgDefine.User selectUser(string uid,string userId)
  {
    import model.User;
    UserRepository  userRep = new UserRepository;
    User user = userRep.findAllByUID(uid);
    auto u =  toUser(user);
    if (u.id != "0")
    {
      auto friendRep = new FriendRepository;
      auto f = friendRep.findByUid(to!int(userId), to!int(u.id));
      if (f !is null)
      {
        u.chatId = to!string(f.chatId);
        u.aliasName = f.aliasName;
      }
    }
    return u;
  }

  static message.MsgDefine.User selectUserByQrCode(string code,string userId)
  {
    import model.User;
    UserRepository  userRep = new UserRepository;
    User user = userRep.findAllByQr(code);
    auto u = toUser(user);
    if (u.id != "0")
    {
      auto friendRep = new FriendRepository;
      auto f = friendRep.findByUid(to!int(userId), to!int(u.id));
      if (f !is null)
      {
        u.chatId = to!string(f.chatId);
        u.aliasName = f.aliasName;
      }
    }
    return u;
  }

  static string makeQrcode(string uid)
  {
    import model.User;
    UserRepository  userRep = new UserRepository;
    return userRep.makeQrcode(to!int(uid));
  }
}

